import socket
import threading
from packetparsers import *

class Listener(threading.Thread):

    def __init__(self,client):
        self.socket = client.socket
        self.packetlist = client.packets
        self.client = client
        threading.Thread.__init__(self)

    def stop(self):
        self.run = False

    def run(self):
        self.run = True
        while self.run:
            data = self.socket.recv(100000)
            if data != '':self.client.recieve_packet(data)

class Client(object):

    packets = []

    expectors = []

    def __init__(self,host, port = 25565):
        self.socket = socket.socket()
        self.listener = Listener(self)
        self.host = host
        self.port = port

    def connect(self):
        self.socket.connect((self.host,self.port))
        self.listener.start()

    def recieve_packet(self,packet):
        opcode = ord(packet[0])
        if opcode in PARSERS:
            parser = PARSERS[opcode]
            data = parser(packet)
            packet = packet(opcode,data)
        else:
            packet = Packet(opcode,None)
        returned = False
        for i in self.expectors:
            if i.opcode == packet.opcode:
                i.packet = packet
                self.expectors.remove(i)
                returned = True
        if not(returned):
            self.packets.append(packet)

    def expect(self,opcode):
        for i in self.packets:
            if i.opcode == opcode:
                self.packets.remove(i)
                return i
        expector = Expector(opcode)
        self.expectors.append(expector)
        while expector.packet == None:pass
        return expector.packet

    def __del__(self):
        self.listener.stop()

    #BEGIN PACKET DEFENITIONS

    def login_request(self,username):
        self.socket.send(login_request(username))

    def handshake(self,username):
        self.socket.send(handshake(username))

    def chat_message(self,message):
        self.socket.send(chat_message(message))

class Packet(object):

    def __init__(self,opcode,data):
        self.opcode = opcode
        self.data = data

class Expector(object):

    packet = None

    def __init__(self,opcode):
        self.opcode = opcode

PARSERS = {
    0x01:parse_login_request,
    0x02:parse_handshake,
    0x03:parse_chat_message,
    0x04:parse_time_update
    }
